<template>
    <PopUps :bgIndex="1000" :boxIndex="1001" widthMy='60%'  height-my="78%">
        <div class="popups-box">
            <div class="header">
                <div class="header-top">
                    <h3>{{ props.popTitle }}</h3>
                    <i class="iconfont icon-icon-cross-empty" @click="closePopUps"></i>
                </div>
                <div class="headerMain">
                    <el-form ref="formRef" :inline="true" :model="popUpsForm" :rules="rules" class="demo-form-inline">
                        <el-form-item :prop="item.name" :label="item.label" v-for="(item, index) in popUpsFormLabel"
                            :key="index" :style="{ 'min-width': `${item.minWidth}'!important'` }">
                            <!-- 输入框 -->
                            <div class="optionsInput">
                            <el-input  v-model="popUpsForm[item.name]" clearable v-if="!item.type || item.type == 'input'"
                               />
                            <el-button v-if="item.btn" class="btnOptions" @click="flag = true">{{ item.btn
                            }}</el-button>
                            </div>
                            <!-- 下拉选框 -->
                            <el-select v-model="popUpsForm[item.name]" clearable v-if="item.type == 'select'"
                                >
                                <el-option :label="item1.label" :value="item1.value" v-for="(item1, index) in item.client"
                                    :key="index" />
                            </el-select>
                            <!-- 日期选框 -->
                            <el-date-picker v-else-if="item.type == 'picker'" v-model="popUpsForm[item.name]" type="date"
                                 placeholder="请输入日期" format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD" />
                        </el-form-item>
                    </el-form>
                </div>
            </div>
            <div class="main">
                <div class="main-top">
                    <h3>商品明细</h3>
                </div>
                <div class="mainContent">
                    <commodityTable :boder="true" :tableTitle="'商品明细编号'" :dataTable="dataTable" @createTable="createTable"
                         @deleteRow="deleteRow" />
                    <el-form ref="formRef1" :rules="rules1" :inline="true" :model="stockroomForm" class="demo-form-inline">
                        <el-form-item :prop="item.name == 'preparedReserves' ? 'preparedReserves' : ''" :label="item.label"
                            v-for="(item, index) in stockroomFormLabel" :class="item.itemClassName" :key="index"
                            :style="{ 'min-width': `${item.minWidth}'!important'` }">
                            <!-- 输入框 -->
                            <el-input v-model="stockroomForm[item.name]" clearable 
                                v-if="!item.type || item.type == 'input'" />
                            <!-- 下拉选框 -->
                            <el-select v-model="stockroomForm[item.name]" clearable v-else-if="item.type == 'select'"
                                >
                                <el-option :label="item1.label" :value="item1.value" v-for="(item1, index) in item.client"
                                    :key="index" />
                            </el-select>
                            <!-- 文本域 -->
                            <el-input v-model="stockroomForm[item.name]" type="textarea" 
                                v-else-if="item.type == 'textarea'" />
                        </el-form-item>

                    </el-form>
                    <div class="btn">
                        <el-button type="primary" @click="onSubmit(formRef)" class="submit">{{ props.popTitle.slice(0, 2)
                        }}</el-button>
                        <el-button type="primary" @click="closePopUps" class="reset">取消</el-button>
                    </div>
                </div>
            </div>
        </div>
    </PopUps>
    <PopUps widthMy='60%'  height-my="78%" v-if="flag" :bgIndex="1002" :boxIndex="1003">
        <div class="optionsOrder">
            <header>选择订单号</header>
            <el-form :inline="true" :model="optionsOrderForm" ref="optionsOrderFormRef" class="form-inline">
                <el-form-item label="下单日期" class="startTime" prop="orderDate">
                    <el-date-picker clearable v-model="optionsOrderForm.orderDate" type="date" format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="单据编号" prop="orderId">
                    <el-input v-model="optionsOrderForm.orderId" />
                </el-form-item>
                <el-form-item label="客户名称" prop="customerId">
                    <el-select v-model="optionsOrderForm.customerId" popper-class="deptIdSelect"
                        @visible-change="selectChange($event, customerId, 'customerName')" clearable>
                        <el-input v-model="customerModel" style="width: 90%"
                            @input="InputSearchChangeHandler(customerId, 'customerName')">
                            <template #prefix>
                                <el-icon class="el-input__icon">
                                    <search />
                                </el-icon>
                            </template>
                        </el-input>
                        <template v-if="customerNameData">
                            <el-option :label="item.customerName" :value="item.customerId" v-for="item in customerNameData"
                                :key="item.customerId" />
                        </template>
                        <template v-if="Array.isArray(customerNameData) && customerNameData.length === 0">
                            <el-option :label="item.customerName" :value="item.customerId" v-for="item in customerId"
                                :key="item.customerId" />
                        </template>
                    </el-select>
                </el-form-item>
                <el-form-item label="部门" prop="deptId">
                    <el-select v-model="optionsOrderForm.deptId" popper-class="deptIdSelect" clearable
                        @visible-change="selectChange($event, deptId, 'deptName')">
                        <el-input v-model="deptIdModel" @input="InputSearchChangeHandler(deptId, 'deptName')"
                            style="width: 90%;">
                            <template #prefix>
                                <el-icon class="el-input__icon">
                                    <search />
                                </el-icon>
                            </template>
                        </el-input>

                        <template v-if="deptIdData">
                            <el-option :label="item.deptName" :value="item.deptId" v-for="item in deptIdData"
                                :key="item.deptId" />

                        </template>
                        <template v-if="Array.isArray(deptIdData) && deptIdData.length === 0">
                            <el-option :label="item.deptName" :value="item.deptId" v-for="item in deptId"
                                :key="item.deptId" />
                        </template>
                    </el-select>
                </el-form-item>
                <el-form-item label="制单人" prop="creator">
                    <el-input v-model="optionsOrderForm.creator" />
                </el-form-item>
                <el-form-item>
                    <div class="btn">
                        <el-button type="primary" @click="onQuery" class="submit">查询</el-button>
                        <el-button type="primary" @click="onReset(optionsOrderFormRef)" color="#E4E9FC"
                            class="reset">重置</el-button>
                    </div>
                </el-form-item>
            </el-form>
            <div class="invoiceStatus">
                <header>单据状态</header>
                <forTableCom :color="color" :idActive="idActive" :bg="bg" @handleSelectionChange="handleSelectionChange"
                    :tableHeaderData="inventoryTableHeaderData" :pagination="false" :tableData="inventoryTableData"
                    height="270" @scrollhandler="scrollhandler" class="forTableComOrder">
                </forTableCom>

                <div class="btnSub">
                    <el-button type="primary" @click="onAdd" class="add">确认</el-button>
                    <el-button type="primary" @click="onCancel" class="cancel" color="#E4E9FC">取消</el-button>
                </div>
            </div>
        </div>
    </PopUps>
</template>
<script setup>
import PopUps from '@/components/My/PopUps';
import commodityTable from './components/commodityTable'
import { reactive, ref, defineEmits, watch, defineProps } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { addInsertProductApi, querySelectSupplierApi } from '@/api/inventory'
import forTableCom from '@/components/forTableCom/index.vue'
import { inputSearchHandler } from '@/hook/inputChange'
import { sliceDate } from '@/utils/date.js'

import { getWorkApi, getdepartmentseApi, getselectOrderApi } from '@/api/tickets/index'
// 选择订单号表单实例
const optionsOrderFormRef = ref(null)
const emit = defineEmits(['popUpsFlase'])
const formRef = ref(null)
const formRef1 = ref(null)
let flag = ref(false)
let props = defineProps(['popTitle', 'disabled'])
// 部门下拉数据
let deptId = ref([])
// 部门绑定的值
let deptIdModel = ref('')
// 部门搜索下拉数据
let deptIdData = ref([])

// 客户名称
let customerId = ref([])
// 客户名绑定的值
let customerModel = ref('')
// 客户搜索下拉数据
let customerNameData = ref([])
// 订单号选择
let optionOrderList = ref()
// 显示搜索到的值
let { SearchHandler } = inputSearchHandler()
// 在 Input 值改变时发送
const InputSearchChangeHandler = (searchValue, i) => {
    // hook
    // SearchHandler(v, arr, searchobj, includesName)
    switch (i) {
        case 'customerName':
            // 客户名
            customerNameData.value = SearchHandler(searchValue, customerModel, i)
            break;
        case 'deptName':
            // 部门
            deptIdData.value = SearchHandler(searchValue, deptIdModel, i)
            break;

        default:
            break;
    }
}
// 封装请求下拉菜单信息
const getDropDownData = (res) => {
    let { code, data } = res
    if (code == 200) {
        return data
    }
}
// 表单
let popUpsForm = ref({
    productInfoId: '后台生成',      // 商品信息编号
    supplierName: '',      // 供应商名称
    stockroomType: '',    // 入库类型
    purchaseDate: '',      // 采购日期
    purchaser: '',                // 采购人
    purchaseType: '',             // 采购类别
    stockroomWarehouse: '',       // 入库仓库
    orderId: '',    // 单据编号
})
// 表单数据标题
let popUpsFormLabel = ref([
    {
        name: 'productInfoId',
        label: '商品信息编号',
        disabled: true
    },
    {
        name: 'supplierName',
        label: '供应商名称',
        type: 'select',
        client: [

        ]
    },
    {
        name: 'stockroomType',
        label: '入库类型',
    },
    {
        name: 'purchaseDate',
        label: '采购日期',
        type: 'picker',
        minWidth: '120px'
    },
    {
        name: 'purchaser',
        label: '采购人',
    },
    {
        name: 'purchaseType',
        label: '采购类别',
    },
    {
        name: 'stockroomWarehouse',
        label: '入库仓库',
    },
    // {
    //     name: 'estimatedDeliveryDate',
    //     label: '预计交付日期',
    //     type: 'picker'
    // },
    {
        name: 'orderId',
        label: '单据编号',
        disabled: true,
        btn: '选择'

    },
])
// 新增表格数据
let dataTable = ref([
    {
        productId: '',   // 商品明细编号
        productName: '',    // 存货名称
        specs: '',          // 规格型号
        unit: '',           // 单位
        price: '',      // 成本单价
        stockroomNumber: '',        // 入库数量
        amount: '',          // 金额
    }
])
// 商品明细表单
let stockroomForm = ref({
    totalPrice: '',      // 总金额
    preferential: '',    // 优惠
    discountedAmount: '',      // 折后金额
    preparedReserves: '',      // 预存数量
    freight: '',       // 运费
    prepayments: '',       // 预付款
    paymentAccount: '',       // 付款账户
    remarks: '',       // 备注
})
// 选择订单表单
const optionsOrderForm = ref({
    orderDate: '',       // 单据日期
    orderId: '',         // 单据编号
    customerId: '',         // 客户名称
    deptId: '',         // 部门
    creator: '',         // 制单人
})
// 选择订单号
const inventoryTableHeaderData = ref([
    {
        prop: 'orderDate',
        label: '单据日期',
    },
    {
        prop: 'orderId',
        label: '单据编号',
    },
    {
        prop: 'customerId',
        label: '客户名称',
    },
    {
        prop: 'businessType',
        label: '业务类型',
    },
    {
        prop: 'productionContent',
        label: '制作内容',
    },
    {
        prop: 'invoiceStatus',
        label: '单据状态',
    },
    {
        prop: 'paymentStatus',
        label: '结款状态',
    },
    {
        prop: 'totalOrderAmount',
        label: '订单总金额',
    },
    {
        prop: 'creator',
        label: '制单人',
    },
])
// 选择订单号的表格数据
const inventoryTableData = ref([

])
// 商品明细表单数据标题
let stockroomFormLabel = ref([
    {
        name: 'totalPrice',
        label: '总金额',
    },
    {
        name: 'preferential',
        label: '优惠',
    },
    {
        name: 'discountedAmount',
        label: '折后金额',
    },
    {
        name: 'preparedReserves',
        label: '预存数量',
    },
    {
        name: 'freight',
        label: '运费',
    },
    {
        name: 'prepayments',
        label: '预付款',
    },
    {
        name: 'paymentAccount',
        label: '付款账户',
    },
    {
        name: 'remarks',
        label: '备注',
        type: 'textarea',
        itemClassName: 'remarks',
    },
])
// 入库信息校验
const rules = reactive({

    supplierName: [
        {
            required: true,
            message: '供应商名称',
            trigger: 'change',
        }
    ],
    stockroomType: [
        {
            required: true,
            message: '入库类型',
            trigger: 'change',
        },
    ],
    purchaseDate: [
        {
            required: true,
            message: '采购日期',
            trigger: 'change',
        },
    ],
    purchaser: [
        {
            required: true,
            message: '采购人',
            trigger: 'change',
        },
    ],
    purchaseType: [
        {
            required: true,
            message: '采购类别',
            trigger: 'change',
        },
    ],
    stockroomWarehouse: [
        {
            required: true,
            message: '入库仓库',
            trigger: 'change',
        },
    ],
    // estimatedDeliveryDate: [
    //     {
    //         required: true,
    //         message: '预计交付日期',
    //         trigger: 'change',
    //     },
    // ],
    orderId: [
        {
            required: true,
            message: '单据编号',
            trigger: 'change',
        },
    ],
})
// 入库信息校验
const rules1 = reactive({
    preparedReserves: [
        {
            required: true,
            message: '预存数量',
            trigger: 'change',
        }
    ]
})
// 创建表格一行表格
const createTable = (data) => {
    if (props.disabled) return
    dataTable.value.push(data)
}
// 删除表格一行表格
const deleteRow = (v) => {
    dataTable.value.splice(v.$index, 1)
}
// 新增
const onSubmit = (formRef) => {
    ElMessageBox.confirm(
        '确认' + props.popTitle + '吗?',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'success',
        }
    ).then(async () => {
        if (!formRef) return
        let condition = await formRef.validate((valid, fields) => {
            if (valid) {
                return true
            } else {
                return false
            }
        })
        let condition1 = await formRef1.value.validate((valid, fields) => {
            if (valid) {
                return true
            } else {
                return false
            }
        })
        if (condition && condition1) {
            // 发送新增请求
            popUpsForm.value.productInfoId = ''
            popUpsForm.value.customerAddress = popUpsForm.value.customerAddress
            let parasm = Object.assign(popUpsForm.value, stockroomForm.value)
            parasm.productVOS = dataTable
            addInsertProductApi(parasm).then(res => {
                popUpsForm.value.productInfoId = '后台生成'
                if (res.code == 200) {
                    emit('getoutboundOrderData')
                    closePopUps()
                    ElMessage({
                        type: 'success',
                        message: res.msg,
                    })
                }
            })
        }
    })
        .catch(() => {
            ElMessage({
                type: 'warning',
                message: '已取消',
            })
        })

}
// 关闭
const closePopUps = () => {
    emit('popUpsFlase', false)
}

// 获取部门下拉菜单数据
const getdeptIdseApiData = async (data = '') => {
    let params = { deptName: data }
    let res = await getdepartmentseApi(params)
    deptId.value = getDropDownData(res)
}
// 第一次进入获取一级二级弹窗的客户下拉数据
const getCustomerData = (res) => {
    customerId.value = getDropDownData(res)
    let rowList = []
    res.data.forEach(v => {
        rowList.push({
            value: v.customerId,
            label: v.customerName
        })
    })
    popUpsFormLabel.value[5].client = rowList
}
// 获取客户下拉菜单数据
const getWorkApiData = async (data = '', contcatData = true) => {
    let params = { 'customerId': data }
    let res = await getWorkApi(params)
    if (contcatData) {
        getCustomerData(res)
    } else {
        // 关联 客户地址 客户电话 客户
        popUpsForm.value.contactPhone = res.data[0].contactPhone
        popUpsForm.value.customerContacts = res.data[0].customerContacts
        popUpsForm.value.customerAddress = res.data[0].address
    }
}

// 选择的列
const handleSelectionChange = (v) => {
    optionOrderList.value = v
}
// 关闭拉下时清除搜索框的值
const selectChange = (event, v, v1) => {
    if (event == false) {
        customerModel.value = ''
        deptIdModel.value = ''
        InputSearchChangeHandler(v, v1)
    }
}
let pageNum = ref(1)    // 页数
let pageSize = ref(50)  // 条数
let totals = ref(12)
// 工单详情接口
const getselectOrderData = async (params = '') => {
    let res = await getselectOrderApi(params)
    let { code, rows, total } = res
    if (code === 200) {
        sliceDate(rows, 'orderDate')
        totals.value = total
        inventoryTableData.value = []
        rows.forEach((v, i) => {
            inventoryTableData.value.push(v)
            inventoryTableData.value[i].businessType = v.productionVOS[0]?.businessType
            inventoryTableData.value[i].productionContent = v.productionVOS[0]?.productionContent
        })
    }
}
// 滑动到底部
const scrollhandler = () => {
    let params = {
        pageNum: pageNum.value++,
        pageSize: pageSize.value + 12
    }
    // 数据请求对比优化
    if (totals.value > inventoryTableData.value.length) {
        getselectOrderData(params)
    }
}
// 选择订单号查询
const onQuery = () => {
    let params = {
        orderDate: optionsOrderForm.value.orderDate,       // 单据日期
        orderId: optionsOrderForm.value.orderId,         // 单据编号
        customerId: optionsOrderForm.value.customerId,         // 客户名称
        deptId: optionsOrderForm.value.deptId,         // 部门
        creator: optionsOrderForm.value.creator,         // 制单人
    }
    console.log(params);
    getselectOrderData(params)
}
// 计算材料安装城管费
watch(dataTable.value, (val) => {
    // 总金额
    let totalMoney = 0
    val.forEach(v => {
        totalMoney += Number(v.amount)
        // 计算每个工单表格 金额
        v.amount = v.stockroomNumber * v.price ? v.stockroomNumber * v.price : 0
    })
    // 总金额
    stockroomForm.value.totalPrice = totalMoney || 0
}, {
    immediate: true,
    deep: true
})
// 选择订单号重置
const onReset = (ref) => {
    if (!ref) return
    ref.resetFields()
}

// 订单号确认
const onAdd = () => {
    if (optionOrderList.value.length == 1) {
        console.log(optionOrderList.value[0]);
        // 订单号
        popUpsForm.value.orderId = optionOrderList.value[0].orderId
        stockroomForm.value.creator = optionOrderList.value[0].creator
        flag.value = false
    } else {
        ElMessage({
            type: 'warning',
            message: '只能勾选一个@^@',
        })
    }
}
// 取消
const onCancel = () => {
    flag.value = false
}



const querySelectSupplierApiFn = async () => {
    let { code, rows } = await querySelectSupplierApi()
    if (code == 200) {
        rows.forEach(v => {
            popUpsFormLabel.value[1].client.push({
                label: v.supplierName,
                value: v.supplierId
            })
        })

    }
}

onMounted(() => {
    querySelectSupplierApiFn()
    getdeptIdseApiData()
    getselectOrderData()
    getWorkApiData()
})
</script>

<style lang="scss" scoped>

.el-input__wrapper {
    --el-select-width: 220px;
}

:deep(.el-form-item) {
    width: 250px;
}

:deep(.el-form-item__label) {
    width: 150px;
    text-align: right;
}

@mixin publicH3 {
    font-weight: 550;
    position: relative;
    font-size: 16px !important;


    &::after {
        content: '';
        width: 5px;
        height: 20px;
        background-color: #1947FF;
        border-radius: 5px;
        position: absolute;
        left: -15px;
        top: 0px;
    }
}

@mixin titlePadding {
    padding: 25px 25px 25px 45px;
}

@mixin pubilcForm {
    :deep(.el-form-item) {
        margin-right: 30px !important;
    }

    :deep(.el-form-item__label) {
        font-size: 14px;
    }

    :deep(.el-input__wrapper) {
        width: 132px;
    }

    :deep(.el-date-editor--datetimerange) {
        width: 240px;
    }

    :deep(.el-table .el-table__header-wrapper th, .el-table .el-table__fixed-header-wrapper th) {
        font-size: 15px !important;
    }
}

.optionsInput {
            display: flex;
            align-items: center;

            .btnOptions {
                background-color: #829BFF;
                color: #fff;
                margin-left: 15px;
                width: 50px;
                height: 25px;

            }
        }
.popups-box {
    .header {
        .header-top {
            position: sticky;
            top: 0px;
            background-color: #fff;
            z-index: 2024;
            @include titlePadding;
            display: flex;
            align-items: center;
            justify-content: space-between;

            h3 {
                @include publicH3;
            }

            .iconfont {
                color: #666;
                font-size: 27px;
            }
        }

        .headerMain {
            .demo-form-inline {
                @include pubilcForm;
            }
        }
    }

    .main {
        .main-top {
            @include titlePadding;

            h3 {
                @include publicH3;
            }
        }



        .mainContent {
            padding: 0 20px 20px 20px;

            .remarks {
                width: 400px;
            }

            .demo-form-inline {
                margin-top: 20px;
                @include pubilcForm;

            }

            .btn {
                text-align: right;

                .el-button {
                    width: 50px;
                    height: 25px;
                    font-size: 12px;
                }

                .reset {
                    background-color: #E4E9FC;
                    color: #333;
                    border: none;
                }
            }
        }
    }
}

.forTableComOrder {
    padding: 0;
}

.optionsOrder {
    padding: 20px 20px 0 20px;

    header {
        margin-bottom: 20px;
        font-weight: 550;
    }



    .btnSub {
        width: 100%;
        text-align: right;
        margin-top: 30px;

        .el-button {
            width: 50px;
            height: 25px;
            font-size: 12px;
        }
    }
}</style>